import re # Slider Task # List of sliders num_sliders = 2 # Read in the file with open('models.py', 'r', encoding='utf-8') as f: filedata = f.read() result = re.search('num_sliders = (\d+) # Number of sliders', filedata) result = result[0] print(result) # Replace the target string filedata = filedata.replace(result, 'num_sliders = '+str(num_sliders)+' # Number of sliders') # Write the file out again with open('models.py', 'w', encoding='utf-8') as f: f.write(filedata) # Read in the new file with open('models.py', 'r', encoding='utf-8') as f: filedata = f.read() result = re.search('num_sliders = (\d+) # Number of sliders', filedata) result = result[0] print(result) # Create Slider Fields slider_list = [] for i in range(1, num_sliders + 1): slider_list.append('slider' + str(i)) print(slider_list) with open('slider_fields.txt', 'w', encoding='utf-8') as f: f.write('# Insert_Sliders_Start\r') for slider in slider_list: with open('slider_fields.txt', 'a', encoding='utf-8') as f: f.write( ' '+slider + ' = models.IntegerField(\r min=random_min(), max=random_max(),\r widget=widgets.Slider(),\r initial=random_initial())\r') with open('slider_fields.txt', 'a', encoding='utf-8') as f: f.write(' # Insert_Sliders_End') with open('slider_fields.txt', 'r', encoding='utf-8') as f: new_slider_fields = f.read() # Replace Slider Fields in models.py # Read in the models.py file with open('models.py', 'r', encoding='utf-8') as f: old_model = f.read() old_slider_fields = re.search('(?s)(# Insert_Sliders_Start)(.*)(# Insert_Sliders_End)', old_model) old_slider_fields = old_slider_fields[0] print(old_slider_fields) # Replace the target string new_model = old_model.replace(old_slider_fields, new_slider_fields) # Write the file out again with open('models.py', 'w', encoding='utf-8') as f: f.write(new_model) # Read in the models.py file with open('models.py', 'r', encoding='utf-8') as f: new_model = f.read() new_slider_fields = re.search('(?s)(?<=# Insert_Sliders_Start)(.*)(?=# Insert_Sliders_End)', new_model) new_slider_fields = new_slider_fields[0] print(new_slider_fields)